package com.hedl.classroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hedl.classroom.base.exception.CommonResult;
import com.hedl.classroom.base.exception.OnlinecClassroomException;
import com.hedl.classroom.base.model.PageParams;
import com.hedl.classroom.base.model.PageResult;
import com.hedl.classroom.mapper.*;
import com.hedl.classroom.model.dto.AddCourseDto;
import com.hedl.classroom.model.dto.CourseBaseInfoDto;
import com.hedl.classroom.model.dto.EditCourseDto;
import com.hedl.classroom.model.dto.QueryCourseParamsDto;
import com.hedl.classroom.model.po.*;
import com.hedl.classroom.service.CourseBaseInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Slf4j
@Service
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {

    @Resource
    private CourseBaseMapper courseBaseMapper;

    @Resource
    private CourseMarketMapper courseMarketMapper;

    @Resource
    private CourseCategoryMapper courseCategoryMapper;

    @Resource
    private TeachplanMapper teachplanMapper;

    @Resource
    private TeachplanMediaMapper teachplanMediaMapper;

    @Resource
    private CourseTeacherMapper courseTeacherMapper;

    /**
     * 课程分页查询
     * @param pageParams    分页信息
     * @param courseParamsDto   查询条件
     * @param companyId 机构id
     * @return  查询结果
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId, PageParams pageParams, QueryCourseParamsDto courseParamsDto) {
        //查询条件
        //拼装查询条件
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        //根据名称模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(courseParamsDto.getCourseName())
                ,CourseBase::getName,courseParamsDto.getCourseName());
        //课程的审核状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(courseParamsDto.getAuditStatus())
                ,CourseBase::getAuditStatus,courseParamsDto.getAuditStatus());
        //按课程发布状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(courseParamsDto.getPublishStatus())
                ,CourseBase::getStatus,courseParamsDto.getPublishStatus());
        queryWrapper.orderByDesc(CourseBase::getChangeDate);

        //根据培训机构id拼装查询条件
        queryWrapper.eq(CourseBase::getCompanyId,companyId);

        //创建page分页参数对象,当前页码，每页记录数
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());

        //开始进行分页查询
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);

        PageResult<CourseBase> courseBasePageResult = new PageResult<>(pageResult.getRecords(),pageResult.getTotal(),pageParams.getPageNo(), pageParams.getPageSize());

        log.info("分页完成的数据：{}",courseBasePageResult);

        return courseBasePageResult;
    }

    /**
     * 新增课程
     * @param companyId 机构ID
     * @param addCourseDto  课程信息
     * @return  课程详细信息
     */
    @Override
    @Transactional
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {
        //向课程基本信息表course_base写入数据
        CourseBase courseBase = new CourseBase();
        //使用get，set写入太麻烦了，直接使用拷贝
        BeanUtils.copyProperties(addCourseDto,courseBase);  //只要属性名一致就可以拷贝
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());
        courseBase.setChangeDate(LocalDateTime.now());
        //审核状态，未审核
        courseBase.setAuditStatus("202002");
        //发布状态，未发布
        courseBase.setStatus("203001");
        //插入数据
        int insert = courseBaseMapper.insert(courseBase);
        if (insert <= 0){
            OnlinecClassroomException.cast("课程添加失败!");
        }

        //向课程营销表course_market写数据
        CourseMarket courseMarket = new CourseMarket();
        //将页面输入的数据拷贝到courseMarket
        BeanUtils.copyProperties(addCourseDto,courseMarket);
        //主键的课程id
        Long courseId = courseBase.getId();
        courseMarket.setId(courseId);
        int i = saveCourseMarket(courseMarket);

        //从数据库查询课程的详细信息,包括两部分
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseId);


        return courseBaseInfo;
    }

    //查询课程信息
    @Override
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId){
        //连表查询
        CourseBaseInfoDto courseBaseInfoDto = courseBaseMapper.queryCourseBaseAndCourseMarket(courseId);
        if (courseBaseInfoDto == null){
            OnlinecClassroomException.cast("数据插入失败!");
        }
        //通过courseCategoryMapper查询分类信息，将分类名称放到CourseBaseInfoDto对象
        //课程分类的名称设置到courseBaseInfoDto
        CourseBaseInfoDto courseCategoryName = courseCategoryMapper.queryCourseCategoryName(courseBaseInfoDto.getSt());
        courseBaseInfoDto.setStName(courseCategoryName.getStName());
        courseBaseInfoDto.setMtName(courseCategoryName.getMtName());

        return courseBaseInfoDto;
    }

    //单独写一个方法保存营销信息；逻辑：存在则更新，不存在就添加
    private int saveCourseMarket(CourseMarket courseMarket){
        //参数合法性校验
        String charge = courseMarket.getCharge();
        if (StringUtils.isEmpty(charge)){
            OnlinecClassroomException.cast("收费规则为空!");
        }
        //如果课程收费，价格没有填写就需要抛出异常
        if (charge.equals("201001")){
            if (courseMarket.getPrice() == null || courseMarket.getPrice().floatValue() <= 0){
                OnlinecClassroomException.cast("课程价格不能为空且价格必须大于0!");
            }
        }

        //从数据库查询营销信息，存在则更新，不存在就添加
        CourseMarket courseMarketNew = courseMarketMapper.selectById(courseMarket.getId());
        if (courseMarketNew == null){
            //插入数据
            int i = courseMarketMapper.insert(courseMarket);
            if (i <= 0){
                OnlinecClassroomException.cast("插入营销数据失败!");
            }
            return i;
        }else {
            //将courseMarket拷贝到courseMarketNew
            BeanUtils.copyProperties(courseMarket,courseMarketNew);
            courseMarketNew.setId(courseMarket.getId());
            //更新
            int i = courseMarketMapper.updateById(courseMarketNew);
            return i;
        }
    }

    /**
     * 根据id查询课程信息和营销信息
     * @param id    主键id
     * @return  课程信息和营销信息
     */
    @Override
    public CourseBaseInfoDto queryById(Long id) {
        return getCourseBaseInfo(id);
    }

    /**
     * 修改课程和营销信息
     * @param editCourseDto 课程和营销更改数据
     * @return  返回修改成功的数据
     */
    @Override
    @Transactional
    public CourseBaseInfoDto updateCourseBaseAndCourseMarket(Long companyId,EditCourseDto editCourseDto) {
        CourseBase courseBase1 = courseBaseMapper.selectById(editCourseDto.getId());
        if (courseBase1 == null){
            OnlinecClassroomException.cast("课程不存在!");
        }

        //机构校验
        if (!companyId.equals(courseBase1.getCompanyId())){
            OnlinecClassroomException.cast("本机构的只能修改本机构的课程");
        }

        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(editCourseDto,courseBase);
        courseBase.setChangeDate(LocalDateTime.now());

        int i = courseBaseMapper.updateById(courseBase);
        if (i <=0 ){
            OnlinecClassroomException.cast("更新课程失败！");
        }
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto,courseMarket);
        if (courseMarket.getCharge().equals("201000")){
            courseMarket.setPrice(0f);
        }
        courseMarketMapper.updateById(courseMarket);
        return getCourseBaseInfo(editCourseDto.getId());
    }

    @Override
    @Transactional
    public CommonResult deleteCourseBase(Long courseId, Long companyId) {
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (!companyId.equals(courseBase.getCompanyId())){
            OnlinecClassroomException.cast("只允许删除本机构的课程！");
        }
        //删除课程信息
        courseBaseMapper.deleteById(courseId);

        //删除课程营销信息
        courseMarketMapper.deleteById(courseId);

        //删除课程计划
        LambdaQueryWrapper<Teachplan> teachplanQueryWrapper = new LambdaQueryWrapper<>();
        teachplanQueryWrapper.eq(Teachplan::getCourseId,courseId);
        teachplanMapper.delete(teachplanQueryWrapper);

        //删除课程计划和关联信息
        LambdaQueryWrapper<TeachplanMedia> teachplanMediaQueryWrapper = new LambdaQueryWrapper<>();
        teachplanMediaQueryWrapper.eq(TeachplanMedia::getCourseId,courseId);
        teachplanMediaMapper.delete(teachplanMediaQueryWrapper);

        //删除课程师资
        LambdaQueryWrapper<CourseTeacher> courseTeacherQueryWrapper = new LambdaQueryWrapper<>();
        courseTeacherQueryWrapper.eq(CourseTeacher::getCourseId,courseId);
        courseTeacherMapper.delete(courseTeacherQueryWrapper);

        return CommonResult.result();
    }
}
